package dev.projectnightfall.network;

import dev.projectnightfall.main.ConsoleLog;
import dev.projectnightfall.thread.IThread;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;

/**
 * General class to handle the socket connection as well as input and output.
 */
public class SocketConnection implements IThread {

    private String serverIP = "";
    private int serverPort = 2012;
    private String serverAddress = "";
    private Socket connection;
    private boolean loopThread;
    private InputHandler input;
    private OutputHandler output;

    /**
     * Basic constructor that sets the server address.
     *
     * @param address Address of the server (IP and port combined. Eg.
     * 192.168.1.1:8080)
     */
    public SocketConnection(String address) {
        serverAddress = address;
    }

    /**
     * Initialises the class.
     */
    public void initialise() {
        String[] addressData = serverAddress.split(":");
        if (addressData.length == 2) {
            serverIP = addressData[0];
            try {
                serverPort = Integer.parseInt(addressData[1]);
            } catch (Exception ex) {
                ConsoleLog.print("Provided server port '" + addressData[1] + "' not valid, using default.", Level.WARNING);
            }
        } else {
            serverIP = serverAddress;
        }
        loopThread = false;
        try {
            connection = new Socket(serverIP, serverPort);
            input = new InputHandler(connection.getInputStream());
            output = new OutputHandler(connection.getOutputStream());
            new Thread(input).start();
            new Thread(output).start();
            new Thread(this).start();
        } catch (UnknownHostException ex) {
            ConsoleLog.print("Failed to locate server '" + serverIP + ":" + serverPort + "'.", Level.SEVERE);
            if (ConsoleLog.isDebug()) {
                ex.printStackTrace();
            }
        } catch (IOException ex) {
            ConsoleLog.print("IOException occured on server '" + serverIP + ":" + serverPort + "'.", Level.SEVERE);
            if (ConsoleLog.isDebug()) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * Method called when .start() is called.
     */
    @Override
    public void run() {
        do {
            //will handle in future commit, was initially going to be the initialiser for input and output :? not sure anymore >.>
        } while (loopThread);
    }

    /**
     * Halts the thread.
     */
    @Override
    public void stopThread() {
        loopThread = false;
    }
}
